
<template>
  <!-- 读音训练 -->
  <div class="diction-training">
    <div class="unit-select common-select">
      <span>选择单元: </span>
      <el-select
        v-model="value"
        @change="changeGetWord"
        clearable
        placeholder="请选择"
      >
        <el-option label="全部" :value="null"> </el-option>
        <el-option
          v-for="item in unitList"
          :key="item.unit_id"
          :label="item.unit_name"
          :value="item.unit_id"
        >
        </el-option>
      </el-select>
    </div>
    <div class="common-table common-pagination">
      <el-table border stripe :data="wordData.list" style="width: 100%">
        <el-table-column
          type="index"
          label="序号"
          width="80px"
          :index="indexMethod"
        >
        </el-table-column>
        <el-table-column prop="word_name" label="单词">
          <el-table-column prop="paraphrase" label="词义">
            <template slot-scope="scope">
              <div class="word-box cell-box">
                <span class="table-text">{{ scope.row.word_name }}</span>
                <span
                  v-for="(item, index) in scope.row.paraphrase.split('\n')"
                  :key="index"
                  class="table-text"
                >
                  <span>{{ item }}</span>
                </span>
              </div>
            </template>
          </el-table-column>
        </el-table-column>

        <!-- <el-table-column prop="phonetic" label="音标">
          <template slot-scope="scope">
            <span v-if="scope.row.phonetic">[{{ scope.row.phonetic }}]</span>
            <span v-else>-</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="audioURL" label="原音" width="150px">
          <template slot-scope="scope">
            <div class="table-cell-box">
              <div
                class="play-audio-box"
                :class="hasRecording ? 'not-click' : 'click'"
                @click="
                  playAudio('audioPlay' + scope.row.word_id + scope.row.index)
                "
              >
                <AudioPlay
                  :type="4"
                  :audioSrc="baseURL + scope.row.audioURL"
                  :disabled="hasRecording"
                  :isClick="false"
                  :ref="'audioPlay' + scope.row.word_id + scope.row.index"
                ></AudioPlay>
                <span>听读音</span>
              </div>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="audioURL" label="录音" width="80px">
          <template slot-scope="scope">
            <div v-if="$store.getters.isTeacher">-</div>
            <div v-else>
              <AudioRecord
                @start="handleStart"
                @ended="handleEnd"
                @clickStart="audioRecordStart(scope.row)"
                @clickEnd="audioRecordEnd(scope.row)"
                @beforeSatrt="beforeRecordSatrt"
                :ref="`audioRecord${scope.row.word_id}-${scope.row.index}`"
                :key="scope.row.word_id"
                :maxTime="10000"
              ></AudioRecord>
            </div>
          </template>
        </el-table-column>
        <el-table-column
          prop="student_sound_record_url"
          label="我的录音"
          width="80px"
        >
          <template slot-scope="scope">
            <div>
              <AudioPlay
                v-if="scope.row.student_sound_record_url"
                :type="2"
                :audioSrc="assetsURL + scope.row.student_sound_record_url"
                :disabled="hasRecording"
              ></AudioPlay>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="得分" width="80px">
          <template slot-scope="scope">
            <div class="word-box cell-box">
              {{ scope.row.score }}
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="last_time" label="最后录音时间" width="160px">
          <template slot-scope="scope">
            <div class="word-box cell-box">
              <span v-if="scope.row.last_time">
                {{scope.row.last_time}}
                <!-- {{ $moment(scope.row.last_time).fromNow() }} -->
              </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="last_time" label="详细" width="80px">
          <template slot-scope="scope">
            <div class="word-box cell-box">
              <span
                v-if="scope.row.last_time"
                class="click green-text"
                @click="checkWordScoreData(scope.row)"
              >
                查看
              </span>
            </div>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        v-if="showPagination"
        class="fr"
        background
        layout="prev, pager, next"
        :total="wordData.total_num"
        @current-change="handleCurrentChange"
        hide-on-single-page
        :page-size="wordParams.pageSize"
      >
      </el-pagination>
    </div>
    <WordReadScore ref="wordReadScore"></WordReadScore>
  </div>
</template>
<script>
import { getTrainingList, getTrainingScore } from "@/api/index";
import AudioPlay from "@/components/AudioPlay";
import AudioRecord from "@/components/AudioRecord";
import WordReadScore from "./wordReadScore";
export default {
  data() {
    return {
      value: null,
      wordNameShow: false,
      wordParapShow: false,
      wordData: {
        total_num: 0,
        list: [],
        total_page: 0,
      },
      isFixed: true,
      wordParams: {
        pageNum: 1,
        pageSize: 15,
      },
      showPagination: true,
      hasRecording: false,
    };
  },
  computed: {},
  props: {
    unitList: {
      type: Array,
      default: function () {
        return [];
      },
    },
    initValue: {
      type: Number,
      default: null,
    },
    checkedBookData: {
      tyep: Object,
    },
  },
  components: {
    AudioPlay,
    AudioRecord,
    WordReadScore,
  },
  methods: {
    checkWordScoreData(data) {
      this.$refs.wordReadScore.show(data);
    },
    playAudio(refName) {
      if (this.$refs[refName]) {
        this.$refs[refName].playAudio();
      }
    },
    wordNameShowChange(value) {
      this.wordNameShow = value;
    },
    handleStart() {
      console.log("开始");
      this.hasRecording = true;
    },
    handleEnd() {
      console.log("结束");
      this.hasRecording = false;
    },
    // 点击录音开始前的回调
    beforeRecordSatrt() {
      this.wordData.list.forEach((item) => {
        if (this.$refs[`audioRecord${item.word_id}-${item.index}`]) {
          this.$refs[`audioRecord${item.word_id}-${item.index}`].stopRecorder();
        }
      });
    },
    // 点击开始录音的回调
    audioRecordStart() {
      console.log("点击开始");
      //
    },
    // 点击结束录音的回调
    // http://localhost:8101/sound/save?word_id=121&word_name=testcc&is_child=1&accent=1
    audioRecordEnd(wordData) {
      console.log("点击结束");
      let params = {
        word_id: wordData.word_id,
        word_name: wordData.word_name,
        is_child: 0,
        accent: this.$store.getters.isBritish == 1 ? 1 : 2,
      };
      let blob =
        this.$refs[
          `audioRecord${wordData.word_id}-${wordData.index}`
        ].getMp3Data();
      let file = new window.File([blob], wordData.word_name + ".mp3", {
        type: blob.type,
      });
      let formData = new FormData();
      formData.append("sound_file", file);
      getTrainingScore(params, formData).then((res) => {
        if (res.code == 200 && res.data) {
          wordData.student_sound_record_url = null;
          wordData.fileData = window.URL.createObjectURL(blob);
          if (
            res.data.context &&
            res.data.context.lines &&
            res.data.context.lines[0] &&
            res.data.context.lines[0].words
          ) {
            wordData.detail =res.data.context.lines[0].words;
          }
          let data = Object.assign(wordData, res.data);
          // 弹框
          this.checkWordScoreData(data);
          this.getTrainingList();
        }
      });
    },

    handleCurrentChange(value) {
      this.wordParams.pageNum = value;
      this.getTrainingList();
    },
    indexMethod(index) {
      return (
        (this.wordParams.pageNum - 1) * this.wordParams.pageSize + index + 1
      );
    },
    changeGetWord() {
      this.showPagination = false;
      this.wordParams.pageNum = 1;
      this.$nextTick(() => {
        this.showPagination = true;
      });
      this.getTrainingList();
    },
    getTrainingList() {
      let data = {
        page_require: {
          page_size: this.wordParams.pageSize,
          page_num: this.wordParams.pageNum,
        },
        book_id: this.checkedBookData.book_id,
        unit_id: this.value ? this.value : null,
      };
      getTrainingList(data).then((res) => {
        if (res.code == 200 && res.data) {
          res.data.list = res.data.list.map((item, index) => {
            item.index = index;
            item.phonetic =
              this.$store.getters.isBritish == 1
                ? item.phonetic_british
                : item.phonetic_american;
            item.audioURL =
              this.$store.getters.isBritish == 1 ? item.en_url : item.us_url;
            // checkedData.detail.details.word
            if (
              item.detail &&
              item.detail.lines &&
              item.detail.lines[0] &&
              item.detail.lines[0].words
            ) {
              item.detail = item.detail.lines[0].words
            } else {
              item.detail = null;
            }
            return item;
          });
          this.wordData = res.data;
        }
      });
    },
    /**
     *  获取麦克风权限
     * */
    getPermission() {
      this.$Recorder.getPermission().then(
        () => {
          console.log("获取权限成功");
        },
        (error) => {
          console.log(`${error.name} : ${error.message}`);
          if (error.name == "NotAllowedError") {
            this.$message({
              type: "error",
              message: `没有使用麦克风的权限`,
            });
          } else if (
            error.name == "NotFoundError" &&
            error.message == "Requested device not found"
          ) {
            this.$message({
              type: "error",
              message: `没有找到麦克风`,
            });
          } else {
            this.$message({
              type: "error",
              message: `${error.name} : ${error.message}`,
            });
          }
        }
      );
    },
  },
  created() {
    // this.getPermission();
  },
  mounted() {},
  watch: {
    initValue: {
      handler() {
        this.value = this.initValue;
        this.getTrainingList();
      },
      //   immediate: true,
    },
  },
};
</script>